import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Card,
  CardContent,
  Grid,
  Chip,
  CircularProgress,
  Alert,
  Button
} from '@mui/material';
import { 
  ArrowBack, 
  DirectionsCar, 
  LocationOn,
  Battery20,
  Speed,
  Thermometer
} from '@mui/icons-material';
import { apiRequest } from '../utils/api';
import { useNavigate, useParams } from 'react-router-dom';


const VehicleDetail = () => {
  const [vehicle, setVehicle] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [latestData, setLatestData] = useState(null);
  const navigate = useNavigate();
  const { id } = useParams();

  useEffect(() => {
    loadVehicleDetail();
  }, [id]);

  // 模拟数据 - 当API请求失败时使用
  const mockVehicleData = {
    id: id || 'mock-vehicle-1',
    licensePlate: '川B29W50',
    brand: '本田',
    model: '雅阁',
    year: '2014',
    color: '黑色',
    vin: '1HGCR2F3XEA000000',
    mileage: 12500,
    status: 'ACTIVE',
    fuelType: '汽油',
    vehicleType: '轿车',
    engine: '2.0L 自然吸气',
    transmissionType: 'CVT自动',
    lastMaintenance: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(), // 30天前
    nextMaintenanceDate: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString(), // 90天后
    ownerName: '张三',
    ownerPhone: '13800138000',
    createdAt: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString(), // 1年前
    updatedAt: new Date().toISOString()
  };

  const mockRealtimeData = {
    id: 'mock-realtime-1',
    vehicleId: id || 'mock-vehicle-1',
    speed: 0,
    batteryLevel: 0,
    temperature: 65,
    location: {
      address: '未知',
      latitude: 30.5728,
      longitude: 104.0668
    },
    timestamp: new Date().toISOString()
  };

  const loadVehicleDetail = async () => {
    try {
      setLoading(true);
      setError(null);
      
      // 获取车辆基本信息
      const vehicleResponse = await apiRequest.get(`/api/vehicles/${id}`);
      setVehicle(vehicleResponse.data);
      
      // 获取车辆实时数据
      const dataResponse = await apiRequest.get(`/api/vehicle-data/vehicle/${id}`);
      if (dataResponse.data && dataResponse.data.length > 0) {
        setLatestData(dataResponse.data[dataResponse.data.length - 1]);
      }
    } catch (err) {
      console.error('Error loading vehicle detail:', err);
      // 使用模拟数据确保页面能显示
      setVehicle(mockVehicleData);
      setLatestData(mockRealtimeData);
      setError(`加载车辆详情失败: ${err.message || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  const formatTimestamp = (timestamp) => {
    if (!timestamp) return '';
    
    // 记录传入的时间戳，以便调试
    console.log('Processing timestamp:', timestamp, 'Type:', typeof timestamp);
    
    try {
      // 尝试多种方式解析日期
      let date;
      
      // 1. 如果是数组类型，尝试解析为日期
      if (Array.isArray(timestamp) && timestamp.length >= 3) {
        console.log('Processing array timestamp:', timestamp);
        // 处理数组格式的日期 [年, 月, 日, 时, 分, 秒, 毫秒]
        // 注意：JavaScript的月份是从0开始的，而Java可能是从1开始的
        const year = timestamp[0];
        // 检查月份是否可能从1开始，如果小于13则认为是Java格式
        const month = timestamp[1] < 13 ? timestamp[1] - 1 : timestamp[1];
        const day = timestamp[2];
        const hour = timestamp[3] || 0;
        const minute = timestamp[4] || 0;
        const second = timestamp[5] || 0;
        const ms = timestamp[6] || 0;
        
        date = new Date(year, month, day, hour, minute, second, ms);
        console.log('Created date from array:', date);
      }
      // 2. 如果是对象类型，尝试获取其值
      else if (typeof timestamp === 'object' && timestamp !== null) {
        // 尝试从对象中提取日期值
        const dateValue = timestamp.value || timestamp.toString();
        console.log('Extracted date value:', dateValue);
        date = new Date(dateValue);
      } else {
        // 3. 直接尝试Date构造函数
        date = new Date(timestamp);
      }
      
      // 3. 如果是LocalDateTime格式(2025-09-03T12:00)
      if (isNaN(date.getTime()) && typeof timestamp === 'string' && timestamp.includes('T')) {
        // 添加完整的时区信息
        const adjustedTimestamp = timestamp.includes('+') ? timestamp : `${timestamp}+00:00`;
        console.log('Adjusted timestamp for LocalDateTime:', adjustedTimestamp);
        date = new Date(adjustedTimestamp);
      }
      
      // 4. 如果是LocalDate格式(2025-09-03)
      if (isNaN(date.getTime()) && typeof timestamp === 'string' && timestamp.match(/^\d{4}-\d{2}-\d{2}$/)) {
        // 添加默认时间和时区
        const adjustedTimestamp = `${timestamp}T12:00:00+00:00`;
        console.log('Adjusted timestamp for LocalDate:', adjustedTimestamp);
        date = new Date(adjustedTimestamp);
      }
      
      // 5. 如果是带有特殊格式的日期字符串
      if (isNaN(date.getTime()) && typeof timestamp === 'string') {
        // 尝试其他可能的格式
        // 例如：Mon Sep 03 2025 12:00:00 GMT+0800
        const formats = [
          /^(\d{4})-(\d{2})-(\d{2})$/,
          /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})$/,
          /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}\.\d{3})$/,
          /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}\.\d{3})([+-]\d{2}:\d{2})$/,
          /^(\w+\s+\w+\s+\d{2}\s+\d{4}\s+\d{2}:\d{2}:\d{2})$/ // Thu Jan 01 1970 00:00:00
        ];
        
        for (let i = 0; i < formats.length && isNaN(date.getTime()); i++) {
          if (formats[i].test(timestamp)) {
            console.log('Matched format pattern:', formats[i].toString());
            date = new Date(timestamp);
            break;
          }
        }
      }
      
      // 检查是否解析成功
      if (isNaN(date.getTime())) {
        console.error('Failed to parse timestamp:', timestamp);
        return '-'; // 使用'-'代替'Invalid Date'
      }
      
      // 只显示年月日（中文格式）
      const formattedDate = date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      });
      console.log('Successfully parsed and formatted (date only):', formattedDate);
      return formattedDate;
    } catch (error) {
      console.error('Error formatting timestamp:', error, 'Timestamp:', timestamp);
      return '-';
    }
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '80vh' }}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>
        <Button onClick={() => navigate('/dashboard')} startIcon={<ArrowBack />}>返回仪表盘</Button>
      </Box>
    );
  }

  if (!vehicle) {
    return (
      <Box sx={{ p: 3 }}>
        <Typography variant="h6" color="error">未找到车辆信息</Typography>
        <Button onClick={() => navigate('/dashboard')} startIcon={<ArrowBack />}>返回仪表盘</Button>
      </Box>
    );
  }

  // 合并车辆数据和实时数据
  // 确保车辆的关键信息（如日期字段）不会被实时数据覆盖
  const vehicleData = {
    // 首先展开车辆基本数据
    ...vehicle,
    // 然后展开实时数据，但避免覆盖关键的车辆信息
    batteryLevel: latestData?.batteryLevel || 0,
    speed: latestData?.speed || 0,
    temperature: latestData?.temperature || 65,
    location: latestData?.location || { address: '北京市朝阳区建国路88号' },
    lastUpdate: formatTimestamp(latestData?.timestamp || vehicle.updatedAt),
    // 确保里程表使用车辆数据
    mileage: vehicle.mileage || 0
  };

  return (
    <Box sx={{ p: 3 }}>
      <Button onClick={() => navigate('/dashboard')} startIcon={<ArrowBack />} sx={{ mb: 2 }}>返回仪表盘</Button>
      
      {/* 顶部车辆信息卡片 */}
      <Card variant="outlined" sx={{ mb: 3 }}>
        <CardContent>
          <Grid container alignItems="center" justifyContent="space-between">
            <Grid item>
              <Typography variant="h5" gutterBottom>欢迎,用户</Typography>
              <Typography variant="h4" color="primary">{vehicleData.licensePlate}</Typography>
              <Typography variant="subtitle2" color="textSecondary">
                最后更新: {vehicleData.lastUpdate}
              </Typography>
            </Grid>
            <Grid item>
              <Chip 
                label={vehicleData.status || '在线'} 
                color="success" 
                size="medium" 
                icon={<DirectionsCar />}
              />
            </Grid>
          </Grid>
          
          <Typography variant="subtitle1" sx={{ mt: 2 }}>
            车型: {vehicleData.model || 'Model 3'} ({vehicleData.year || '2022'})
          </Typography>
          
          {/* 关键指标区域 */}
          <Grid container spacing={3} sx={{ mt: 3 }}>
            <Grid item xs={12} sm={6} md={3}>
              <Card variant="outlined">
                <CardContent>
                  <Typography variant="caption" color="textSecondary">行驶里程</Typography>
                  <Typography variant="h6">{vehicleData.mileage} km</Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={12} sm={6} md={3}>
              <Card variant="outlined">
                <CardContent>
                  <Typography variant="caption" color="textSecondary">电池电量</Typography>
                  <Typography variant="h6">{vehicleData.batteryLevel}%</Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={12} sm={6} md={3}>
              <Card variant="outlined">
                <CardContent>
                  <Typography variant="caption" color="textSecondary">当前速度</Typography>
                  <Typography variant="h6">{vehicleData.speed} km/h</Typography>
                </CardContent>
              </Card>
            </Grid>
            <Grid item xs={12} sm={6} md={3}>
              <Card variant="outlined">
                <CardContent>
                  <Typography variant="caption" color="textSecondary">发动机温度</Typography>
                  <Typography variant="h6">{vehicleData.temperature}°C</Typography>
                </CardContent>
              </Card>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      {/* 车辆详细信息区域 */}
      <Grid container spacing={3}>
        {/* 左侧 - 车辆静态数据 */}
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>车辆静态数据</Typography>
              
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div>
                  <Typography variant="body2" color="textSecondary">车辆类型</Typography>
                  <Typography variant="body1">{vehicleData.vehicleType || '轿车'}</Typography>
                </div>
                <div>
                  <Typography variant="body2" color="textSecondary">燃油类型</Typography>
                  <Typography variant="body1">{vehicleData.fuelType || '电动'}</Typography>
                </div>
                <div>
                  <Typography variant="body2" color="textSecondary">发动机</Typography>
                  <Typography variant="body1">{vehicleData.engine || '双电机'}</Typography>
                </div>
                <div>
                  <Typography variant="body2" color="textSecondary">变速箱</Typography>
                  <Typography variant="body1">{vehicleData.transmissionType || '自动'}</Typography>
                </div>
                <div>
                  <Typography variant="body2" color="textSecondary">注册日期</Typography>
                  <Typography variant="body1">{vehicleData.registrationDate ? formatTimestamp(vehicleData.registrationDate) : '-'}</Typography>
                </div>
                <div>
                  <Typography variant="body2" color="textSecondary">保险到期日</Typography>
                  <Typography variant="body1">{vehicleData.insuranceExpiry ? formatTimestamp(vehicleData.insuranceExpiry) : '-'}</Typography>
                </div>
                <div>
                  <Typography variant="body2" color="textSecondary">上次保养</Typography>
                  <Typography variant="body1">{vehicleData.lastMaintenance ? formatTimestamp(vehicleData.lastMaintenance) : '-'}</Typography>
                </div>
                <div>
                  <Typography variant="body2" color="textSecondary">下次保养</Typography>
                  <Typography variant="body1">{vehicleData.nextMaintenanceDate ? formatTimestamp(vehicleData.nextMaintenanceDate) : '-'}</Typography>
                </div>
              </div>
            </CardContent>
          </Card>
        </Grid>

        {/* 右侧 - 实时数据和位置 */}
        <Grid item xs={12} md={6}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>车辆实时状态</Typography>
              
              <div style={{ marginBottom: 16 }}>
                <Typography variant="subtitle2" gutterBottom>当前位置</Typography>
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
                  <LocationOn color="primary" size={18} style={{ marginRight: 8 }} />
                  <Typography variant="body2">{vehicleData.location.address}</Typography>
                </div>
                <div style={{ height: 200, border: '1px solid #e0e0e0', borderRadius: 4 }}>
                  {/* 简化的地图展示 */}
                  <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%' }}>
                    <LocationOn size={48} color="primary" />
                  </div>
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div>
                  <Typography variant="body2" color="textSecondary">电池电量</Typography>
                  <Typography variant="body1">{vehicleData.batteryLevel}%</Typography>
                </div>
                <div>
                  <Typography variant="body2" color="textSecondary">胎压状态</Typography>
                  <Typography variant="body1">正常</Typography>
                </div>
              </div>
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box>
  );
};

export default VehicleDetail;